async function fetchAllAsin() {
  if (window.searchWordAllAsin) return window.searchWordAllAsin;

  window.searchWordAllAsin = fetch(location.href)
    .then(response => response.text())
    .then(data => {
      window.parentAsin = JSON.parse(`{${data.match(/"parentAsin"\s*\:.*\"/)[0]}}`).parentAsin;
      let dvdd = JSON.parse(`{${data.match(/"dimensionValuesDisplayData"\s*:\s*{.*?}/)[0]}}`).dimensionValuesDisplayData;
      return Object.entries(dvdd).map(item => item[0])
    })
  return window.searchWordAllAsin;
}

async function query(keyword, page, ref=1, qid = Math.floor(Date.now() / 1000)) {
  keyword = encodeURIComponent(keyword)
  ref = ref <= 0 ? 1 : ref
  let url = `${location.origin}/s/query?k=${keyword}&page=${page}&qid=${qid}&ref=sr_pg_${ref}`

  return fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
  .then(response => {
    if (!response.ok) {
      throw new Error('Request failed with status: ' + response.status);
    }
    return response.text().then(text => text.split('&&&').filter(t => {
      try {
        JSON.parse(t)
        return true
      } catch(e) {
        return false
      }
    }).map(t => JSON.parse(t)).filter(i => i[2] && i[2].asin).map(i => i[2]));
  });
}

function getArrayIntersection(arr1, arr2) {
  let set1 = new Set(arr1);
  let set2 = new Set(arr2);
  let intersection = [...set1].filter(item => set2.has(item));
  
  return intersection;
}

async function getRanking(keyword) {
  let allAsins = await fetchAllAsin();
  let qid = Math.floor(Date.now() / 1000) - Math.floor(Math.random() * 600)
  let rankingLeft = 0

  for(let i = 1; i <= 7; i++) {
    let queryRes = await query(keyword, i, i, qid)
    let qAsins = queryRes.map(r => r.asin)

    let sameAsins = getArrayIntersection(allAsins, qAsins)

    if (sameAsins.length > 0) {
      index = queryRes.findIndex(r => sameAsins.includes(r.asin))
      return rankingLeft + index + 1
    }
    rankingLeft += queryRes.length;
  }
  return 999
}

async function getKeywords() {
  let url = `https://api.miraazzurra.com/amazon/search_keywords/keywords?parentAsin=${window.parentAsin}`
  return await fetch(url).then(response => response.json()).then(data => data)
}

async function run() {
  await fetchAllAsin();
  let rankings = []
  let keywords = await getKeywords()
  console.log(keywords)

  for (let i = 0; i < keywords.length; i++) {
    let keyword = keywords[i]
    let ranking = await getRanking(keyword)
    rankings.push({
      keyword: keyword,
      ranking: ranking
    })
  }
  
  chrome.runtime.sendMessage( { action: 'openUrlAndExecScript', data: { parentAsin: window.parentAsin, rankings: rankings } } );
}

run()



